﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ManagedWinapi.Windows;

namespace wutils
{
    public partial class TaskMan : Form
    {
        public string WindowTitle { get { return WindowTitleLbl.Text; } set { WindowTitleLbl.Text = value; } }
        public Panel ButtonsContainer { get { return container; } }
        public TaskMan()
        {
            InitializeComponent();
            Initialize();
        }

        private void Initialize()
        {
            WindowUtils.MinimizedWindowsChanged += MinimizeWindowChanged;
            container.MaximumSize =
                new Size(Screen.PrimaryScreen.WorkingArea.Width - (Screen.PrimaryScreen.WorkingArea.Width / 4),
                Screen.PrimaryScreen.WorkingArea.Height - (Screen.PrimaryScreen.WorkingArea.Height / 4));
        }

        private void MinimizeWindowChanged(object sender, WindowEventArgs e)
        {
            if (e.Action != EventAction.ADDED) return;

            container.Controls.Add(new MinimizedWindowBigButton(e.Window, this));
        }

        public void Rebuild()
        {
            if (container.Controls.OfType<MinimizedWindowBigButton>().Count() == WindowUtils.MinimizedWindows.Count())
                return;

            var btns = new List<MinimizedWindowBigButton>(container.Controls.OfType<MinimizedWindowBigButton>());
            foreach (var btn in btns)
            {
                container.Controls.Remove(btn);
            }
            var windows = new List<SystemWindow>(WindowUtils.MinimizedWindows);
            foreach (var window in windows)
            {
                container.Controls.Add(new MinimizedWindowBigButton(window, this));
            }
        }

        public void Destroy()
        {
            List<MinimizedWindowBigButton> btns = new List<MinimizedWindowBigButton>();
            btns.AddRange(container.Controls.OfType<MinimizedWindowBigButton>());

            foreach (var btn in btns)
            {
                btn.Destroy();
            }
            Dispose();
        }

        public void FocusNext()
        {
            bool brk = false;
            MinimizedWindowBigButton first = null;

            foreach (var btn in container.Controls.OfType<MinimizedWindowBigButton>())
            {
                if (first == null) first = btn;
                if (brk)
                {
                    btn.Focus();
                    brk = false;
                    break;
                }
                if (btn.Focused) brk = true;
            }
            if (brk)
            {
                if (first != null) first.Focus();
            }
        }
    }
}
